# -*- encoding: utf-8 -*-

"""
@File:      tc_libtalloc_libtalloc_func_002.py
@Time:      2024/04/03 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtalloc_libtalloc_func_002.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtalloc libtalloc-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >talloc_test2.c<<"EOF"
#include <talloc.h>
#include <assert.h>
#include <stdio.h>

void test_reference_counting() {
    void *root = talloc_new(NULL);
    void *child = talloc_new(root);
    void *additional_reference = NULL;

    // 引用计数应该初始为0，因为还没有额外引用
    assert(talloc_reference_count(child) == 0);

    // 创建额外引用
    additional_reference = talloc_reference(root, child);
    // 现在引用计数应该为1
    assert(talloc_reference_count(child) == 1);

    // 取消一个额外引用
    talloc_unlink(root, additional_reference);
    // 现在引用计数应该回到0
    assert(talloc_reference_count(child) == 0);

    talloc_free(child);
    talloc_free(root);
}

int main() {
    test_reference_counting();
    
    printf("All tests passed.\\n");
    return 0;
}
EOF'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o talloc_test2 talloc_test2.c -ltalloc")
        code, talloc_result = self.cmd("./talloc_test2")
        self.assertIn('All tests passed', talloc_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf talloc_test2.c talloc_test2")
